<?php
// 设置错误报告
error_reporting(E_ALL);
ini_set('display_errors', 1);

// 设置时区
date_default_timezone_set('Asia/Shanghai');

// 定义根目录
define('ROOT_PATH', dirname(__DIR__));

// 注册自动加载
spl_autoload_register(function ($class) {
    $file = ROOT_PATH . '/src/' . str_replace('\\', '/', $class) . '.php';
    if (file_exists($file)) {
        require $file;
    }
});

// 路由配置
$routes = [
    // 绿波路段管理
    'GET|/sections' => ['Controllers\GreenWaveController', 'getSections'],
    'GET|/sections/{id}' => ['Controllers\GreenWaveController', 'getSectionDetail'],
    'POST|/sections' => ['Controllers\GreenWaveController', 'createSection'],
    'PUT|/sections/{id}' => ['Controllers\GreenWaveController', 'updateSection'],
    'DELETE|/sections/{id}' => ['Controllers\GreenWaveController', 'deleteSection'],
    
    // 绿波计算
    'POST|/sections/{id}/calculate' => ['Controllers\GreenWaveController', 'calculateTimingPlan'],
];

// 获取请求方法和URI
$method = $_SERVER['REQUEST_METHOD'];
$uri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);

// 移除基础路径
$basePath = dirname($_SERVER['SCRIPT_NAME']);
if ($basePath !== '/') {
    $uri = substr($uri, strlen($basePath));
}

// 路由匹配
$matched = false;
foreach ($routes as $pattern => $handler) {
    list($routeMethod, $routePath) = explode('|', $pattern);
    
    // 检查请求方法是否匹配
    if ($routeMethod !== $method) {
        continue;
    }
    
    // 将路由模式转换为正则表达式
    $pattern = preg_replace('/\{([^}]+)\}/', '([^/]+)', $routePath);
    $pattern = str_replace('/', '\/', $pattern);
    $pattern = '/^' . $pattern . '$/';
    
    if (preg_match($pattern, $uri, $matches)) {
        $matched = true;
        
        // 移除完整匹配项
        array_shift($matches);
        
        // 实例化控制器并调用方法
        list($controller, $method) = $handler;
        $instance = new $controller();
        call_user_func_array([$instance, $method], $matches);
        break;
    }
}

// 未找到匹配路由
if (!$matched) {
    header('HTTP/1.1 404 Not Found');
    echo json_encode([
        'code' => 404,
        'message' => '接口不存在',
        'data' => null
    ], JSON_UNESCAPED_UNICODE);
} 